package com.ssfeng.youxia.controller;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by liyuhang on 2019-09-02.
 */
@Controller
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    private MappingJackson2JsonView mappingJackson2JsonView;

    public MappingJackson2JsonView getMappingJackson2JsonView() {
        return mappingJackson2JsonView;
    }

    @Autowired
    public void setMappingJackson2JsonView(MappingJackson2JsonView mappingJackson2JsonView) {
        this.mappingJackson2JsonView = mappingJackson2JsonView;
    }

    /***
     *登录接口
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public ModelAndView login(HttpServletRequest servletRequest,
                              HttpServletResponse servletResponse,
                              String username, String password,
                              Boolean rememberme) {
        logger.error("{}开始登陆",username);
        if (StringUtils.isEmpty(username)) {
            throw new RuntimeException("用户名不能为空!");
        }

        if (StringUtils.isEmpty(password)) {
            throw new RuntimeException("密码不能为空!");
        }

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        if (Boolean.TRUE.equals(rememberme)) {
            token.setRememberMe(true);
        } else {
            token.setRememberMe(false);
        }
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            throw new RuntimeException("账号不存在！", e);
        } catch (DisabledAccountException e) {
            throw new RuntimeException("账号未启用！", e);
        } catch (IncorrectCredentialsException e) {
            throw new RuntimeException("密码错误！", e);
        } catch (Throwable e) {
            throw new RuntimeException(e.getMessage(), e);
        }

        ModelAndView modelAndView = new ModelAndView();
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("code", "-1");
        resultMap.put("msg", "登录失败");
        if (subject.isAuthenticated()) {
            resultMap.put("code", "0");
            resultMap.put("msg", "登录成功");
            resultMap.put("url",servletRequest.getAttribute("basePath").toString() + "tpage/loginSuccess.html");
            modelAndView.setView(mappingJackson2JsonView);
            SavedRequest savedRequest = WebUtils.getSavedRequest(servletRequest);
            if (!org.springframework.util.StringUtils.isEmpty(savedRequest)) {
                logger.debug("requestUrl:{}", savedRequest.getRequestUrl());
                logger.debug("queryString:{}",savedRequest.getQueryString());
                resultMap.put("code", "302");
                resultMap.put("url", savedRequest.getRequestURI());
            }
        }

        modelAndView.addObject("data", resultMap);
        return modelAndView;
    }


    @GetMapping("/unLoginTest")
    @ResponseBody
    public Object unLoginTest(){
        Map<String, Object> map = new HashMap<>();
        map.put("msg", "尚未登录");
        return map;
    }

    /***
     * 退出登录
     * @return
     */
    /*@RequestMapping("/logout")
    @ResponseBody
    public ModelAndView logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setView(mappingJackson2JsonView);
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("code", "0");
        resultMap.put("msg", "退出成功");
        modelAndView.addObject("data", resultMap);
        return modelAndView;
    }*/
}
